package com.yzt.message.custom;

import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.core.text.TextUtilsCompat;

import com.alibaba.fastjson.JSONObject;
import com.yzt.zhuju.network.entity.message.ContentTranslateBean;
import com.yzt.zhuju.widget.GenderAgeView;
import com.yzt.p_base.utils.DisplayUtils;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.yzt.message.R;

import java.util.List;
import java.util.Locale;

import io.rong.imkit.config.RongConfigCenter;
import io.rong.imkit.conversation.extension.component.emoticon.AndroidEmoji;
import io.rong.imkit.model.UiMessage;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imkit.utils.TextViewUtils;
import io.rong.imkit.widget.ILinkClickListener;
import io.rong.imkit.widget.LinkTextViewMovementMethod;
import io.rong.imkit.widget.adapter.IViewProviderListener;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.message.TextMessage;

/**
 * 文本消息
 */
public class CustomTextMessageItemProvider extends CustomBaseMessageItemProvider<TextMessage> {

    int paddingLeft = DisplayUtils.getDimensionPixelSize(R.dimen.dp_14);

    int paddingTop = DisplayUtils.getDimensionPixelSize(R.dimen.dp_9);

    public CustomTextMessageItemProvider() {
        mConfig.showReadState = true;
        mConfig.showContentBubble = false;
    }

    @Override
    protected io.rong.imkit.widget.adapter.ViewHolder onCreateMessageContentViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.nomi_rc_item_destruct_text_message, viewGroup, false);
        return new ViewHolder(view.getContext(), view);
    }

    @Override
    protected void bindMessageContentViewHolder(io.rong.imkit.widget.adapter.ViewHolder viewHolder, io.rong.imkit.widget.adapter.ViewHolder parentHolder,
                                                TextMessage message, UiMessage uiMessage, int position, List<UiMessage> list,
                                                IViewProviderListener<UiMessage> iViewProviderListener) {

        ViewHolder holder = (ViewHolder) viewHolder;
        JSONObject jsonObject = JSONObject.parseObject(message.getExtra());
        String sendBackdrop = null;
        String receiveBackdrop = null;
        String fontColor = null;
        String isAutoMatch = null;

        holder.layoutGroup.setVisibility(View.GONE);
        if (uiMessage.getConversationType() == Conversation.ConversationType.GROUP) {
            String extra = message.getExtra();
            JSONObject json = JSONObject.parseObject(extra);
            if (json != null) {
                try {
                    int age = json.getInteger("age");
                    int gender = json.getInteger("gender");
                    int competence = json.getInteger("competence");
                    holder.viewGender.setUserInfo(gender, age);
                    holder.layoutGroup.setVisibility(View.VISIBLE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        //国际化
        if (TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == 1) {
            holder.message.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_END);
        }

        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) holder.flContent.getLayoutParams();
        LinearLayout.LayoutParams groupLayoutParams = (LinearLayout.LayoutParams) holder.layoutGroup.getLayoutParams();
        layoutParams.setMargins(0, 0, 0, 0);
        if (jsonObject != null) {
            sendBackdrop = jsonObject.getString("sendBackdrop");
            receiveBackdrop = jsonObject.getString("receiveBackdrop");
            fontColor = jsonObject.getString("fontColor");
            isAutoMatch = jsonObject.getString("isAutoMatch");
        }

        holder.message.setTag(uiMessage.getMessageId());
        if (uiMessage.getContentSpannable() == null) {
            SpannableStringBuilder spannable = TextViewUtils.getSpannable(message.getContent(), new TextViewUtils.RegularCallBack() {
                @Override
                public void finish(SpannableStringBuilder spannable) {
                    uiMessage.setContentSpannable(spannable);
                    if (holder.message.getTag().equals(uiMessage.getMessageId())) {
                        holder.message.post(new Runnable() {
                            @Override
                            public void run() {
                                //holder.message.setText(uiMessage.getContentSpannable());
                                if (uiMessage.getContent().getExtra() != null && !"".equals(uiMessage.getContent().getExtra())) {
                                    ContentTranslateBean translateBean = JSONObject.parseObject(uiMessage.getContent().getExtra(), ContentTranslateBean.class);
                                    holder.message.setText(translateBean.getContentTranslate());
                                } else {
                                    holder.message.setText(uiMessage.getContentSpannable());
                                }
                            }
                        });
                    }
                }
            });
            uiMessage.setContentSpannable(spannable);
        }

        if (uiMessage.getContent().getExtra() != null && !"".equals(uiMessage.getContent().getExtra()) && !"{}".equals(uiMessage.getContent().getExtra())) {
            ContentTranslateBean translateBean = JSONObject.parseObject(uiMessage.getContent().getExtra(), ContentTranslateBean.class);
            holder.message.setText(translateBean.getContentTranslate());
        } else {
            holder.message.setText(uiMessage.getContentSpannable());
        }

        holder.message.setMovementMethod(new LinkTextViewMovementMethod(new ILinkClickListener() {
            @Override
            public boolean onLinkClick(String link) {
                boolean result = false;
                if (RongConfigCenter.conversationConfig().getConversationClickListener() != null) {
                    result = RongConfigCenter.conversationConfig().getConversationClickListener().onMessageLinkClick(holder.getContext(), link, uiMessage.getMessage());
                }

                if (result) {
                    return true;
                } else {
                    String str = link.toLowerCase();
                    if (str.startsWith("http") || str.startsWith("https")) {
                        RouteUtils.routeToWebActivity(holder.getContext(), link);
                        result = true;
                    }

                    return result;
                }
            }
        }));

        if (uiMessage.getMessageDirection() == Message.MessageDirection.SEND) {
            layoutParams.gravity = Gravity.END;
            groupLayoutParams.gravity = Gravity.END;

            try {
                if (TextUtils.isEmpty(fontColor)) {
                    holder.message.setTextColor(ContextCompat.getColor(viewHolder.getContext(), R.color.white));
                } else {
                    holder.message.setTextColor(Color.parseColor(fontColor));
                }
            } catch (Exception ignored) {

            }

            if (TextUtils.isEmpty(sendBackdrop)) {
                resetBackground(holder.llMessage, R.drawable.nomi_rc_ic_bubble_right);
            } else {
                ImageLoadUtil.load9Png(holder.llMessage.getContext(), sendBackdrop, R.drawable.nomi_rc_ic_bubble_right, holder.llMessage);
            }

        } else {
            layoutParams.gravity = Gravity.START;
            groupLayoutParams.gravity = Gravity.START;
            try {
                if (TextUtils.isEmpty(fontColor)) {
                    holder.message.setTextColor(ContextCompat.getColor(viewHolder.getContext(), R.color.color_262628));
                } else {
                    holder.message.setTextColor(Color.parseColor(fontColor));
                }
            } catch (Exception ignored) {

            }

            if (TextUtils.isEmpty(receiveBackdrop)) {
                resetBackground(holder.llMessage, R.drawable.nomi_rc_ic_bubble_left);
            } else {
                ImageLoadUtil.load9Png(holder.llMessage.getContext(), receiveBackdrop, R.drawable.nomi_rc_ic_bubble_left, holder.llMessage);
            }
        }

        holder.message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ViewParent parent = holder.itemView.getParent();
                if (parent instanceof View) {
                    ((View) parent).performClick();
                }
            }
        });

        holder.message.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                ViewParent parent = holder.itemView.getParent();
                return parent instanceof View && ((View) parent).performLongClick();
            }
        });
    }

    @Override
    protected boolean onItemClick(io.rong.imkit.widget.adapter.ViewHolder holder, TextMessage message, UiMessage uiMessage, int position, List<UiMessage> list, IViewProviderListener<UiMessage> listener) {
        return false;
    }

    @Override
    protected boolean isMessageViewType(MessageContent messageContent) {
        return messageContent instanceof TextMessage && !messageContent.isDestruct();
    }

    @Override
    public Spannable getSummarySpannable(Context context, TextMessage message) {
        if (message != null && !TextUtils.isEmpty(message.getContent())) {
            String content = message.getContent();
            content = content.replace("\n", " ");
            if (content.length() > 100) {
                content = content.substring(0, 100);
            }

            return new SpannableString(AndroidEmoji.ensure(content));
        } else {
            return new SpannableString("");
        }
    }

    private static class ViewHolder extends io.rong.imkit.widget.adapter.ViewHolder {

        TextView message;
        View llMessage;
        View flContent;
        LinearLayout layoutItem;

        View layoutGroup;
        TextView tvNickname;
        GenderAgeView viewGender;

        public ViewHolder(Context context, View view) {
            super(context, view);
            this.message = view.findViewById(R.id.rc_text);
            this.llMessage = view.findViewById(R.id.ll_message);
            this.flContent = view.findViewById(R.id.fl_content);
            this.layoutItem = view.findViewById(R.id.layout_item);

            this.layoutGroup = view.findViewById(R.id.layout_group);
            this.tvNickname = view.findViewById(R.id.tv_nickname);
            this.viewGender = view.findViewById(R.id.view_gender);
        }
    }

    private void resetBackground(View view, int resid) {
        view.setBackground(null);
        view.setPadding(paddingLeft, paddingTop, paddingLeft, paddingTop);
        if (resid != 0) {
            view.setBackgroundResource(resid);
        }
    }
}
